package com.sixmac.utils;

import com.alibaba.fastjson.JSONObject;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.kit.HttpKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.LockToken;
import com.sixmac.module.LockUser;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class LockManage {

//    static String url = "https://devchat.leocheery.net";
    static String url = "https://devchat.leocheery.net";
    static String companyToken = "/auth-platform/oauth/token";//请求CompanyToken


    static String clientId = "APP0016CD24A106C7D6";
    static String clientSecret = "9583CDA08A2B538482CD2BE831C31D2C";
    static String  common = "/device-platform/oauthClient/device/";


    public static String lockUser ="/lockUser";//控制设备注册锁用户
    public static String changeLockUserInfo = "/changeLockUserInfo";//更新nbiot设备锁用户指纹
    public static String nbiotCtrl = "/nbiotCtrl";//控制设备nbiot开锁



    /**
     * 获取token
     * @return
     */
    public LockToken getToken(){
        List<LockToken> tokens = Blade.create(LockToken.class).findAll();
       boolean isRefer = false;

       if (tokens.size() == 0){
           isRefer = true;
       }

        if ((System.currentTimeMillis()-tokens.get(0).getCreatTime().getTime())/1000*60*60>=1)
            isRefer = true;

        LockToken lockToken = null;
       if (isRefer){
           HashMap tokenMap = token();
           String token = tokenMap.get("access_token").toString();
           Blade.create(LockToken.class).deleteBy(" id>0 ",null);
           lockToken = new LockToken();
           lockToken.setCreatTime(new Date());
           lockToken.setToken(token);
           Blade.create(LockToken.class).save(lockToken);
       }else{
           lockToken = tokens.get(0);
       }
        return lockToken;
    }

    /**
     * 接口刷新token
     * @return
     */
    public HashMap token(){
        HashMap<String,Object> params = new HashMap<>();
        params.put("client_id",clientId);
        params.put("client_secret",clientSecret);
        params.put("scope","read+write");
        params.put("grant_type","client_credentials");
        String param = "client_id="+clientId+"&client_secret="+clientSecret+"&scope=read+write&grant_type=client_credentials";
        String uri=url+companyToken;
        try {
            String result = HttpKit.post(uri,params);
            HashMap data = JsonKit.parse(result, HashMap.class);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加锁用户
     * @param lockUser
     * @return
     */
    public Boolean addUser(LockUser lockUser){
        LockToken token = getToken();

        HashMap<String,String> param = new HashMap<>();
        param.put("lockUserInfo",lockUser.getLockUserInfo());
        param.put("periodWeek",lockUser.getPeriodWeek());
        param.put("periodStartTime",lockUser.getPeriodStartTime());
        param.put("periodEndTime",lockUser.getPeriodEndTime());
        param.put("msgId",lockUser.getMsgId());
        param.put("userFlag",lockUser.getUserFlag());
        param.put("unlockWay",lockUser.getUnlockWay());
        param.put("lockUserType",lockUser.getLockUserType());
        param.put("startDay",lockUser.getStartDay());
        param.put("endDay",lockUser.getEndDay());

        try {

            for (int i = 0;i<15;i++){
                String result = HttpClientKit.post(url+common+lockUser.getDeviceCode()+LockManage.lockUser,param,"utf8",token.getToken());
                System.out.println("录入指纹返回："+result);
                JSONObject data = JsonKit.parse(result);
                Boolean results = data.getBoolean("result");
                Integer status = data.getInteger("status");
                if (results){
                    return true;
                }
                i++;
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除锁用户
     * @param lockUser
     * @return
     */
    public HashMap deleteUser(LockUser lockUser){
        LockToken token = getToken();

        HashMap<String,String> param = new HashMap<>();
        param.put("msgId",lockUser.getMsgId());
        try {
            String result = HttpClientKit.delete(url+common+lockUser.getDeviceCode()+LockManage.lockUser+"/"+lockUser.getLockUserInfo()+"?msgId="+lockUser.getMsgId(),token.getToken());
            JSONObject data = JsonKit.parse(result);
            System.out.println("传入参数："+param);
            System.out.println("删除指纹返回："+result);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改锁用户
     * @param lockUser
     * @return
     */
    public HashMap updateUser(LockUser lockUser){
        LockToken token = getToken();

        HashMap<String,String> param = new HashMap<>();
        param.put("lockUserInfo",lockUser.getLockUserInfo());
        param.put("periodWeek",lockUser.getPeriodWeek());
        param.put("periodStartTime",lockUser.getPeriodStartTime());
        param.put("periodEndTime",lockUser.getPeriodEndTime());
        param.put("msgId",lockUser.getMsgId());
        param.put("userFlag",lockUser.getUserFlag());
        param.put("unlockWay",lockUser.getUnlockWay());
        param.put("lockUserType",lockUser.getLockUserType());
        param.put("startDay",lockUser.getStartDay());
        param.put("endDay",lockUser.getEndDay());

        try {
            String result = HttpClientKit.post(url+common+lockUser.getDeviceCode()+LockManage.lockUser+"/"+lockUser.getLockUserInfo(),param,"utf8",token.getToken());
            JSONObject data = JsonKit.parse(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加指纹
     * @param lockUser
     * @return
     */
    public boolean addFingerprint(LockUser lockUser){
        LockToken token = getToken();

        HashMap<String,String> param = new HashMap<>();
        param.put("msgId",lockUser.getMsgId());
        param.put("userAccount",lockUser.getUserAccount());

        try {
            String result = HttpClientKit.post(url+common+lockUser.getDeviceCode()+LockManage.lockUser+"/"+lockUser.getLockUserInfo()+changeLockUserInfo,param,"utf8",token.getToken());
            JSONObject data = JsonKit.parse(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 控制开锁
     * @param lockUser
     * @return
     */
    public Boolean openLock(LockUser lockUser){
        LockToken token = getToken();
        HashMap<String,String> param = new HashMap<>();
        param.put("msgId",lockUser.getMsgId());
        param.put("userFlag",lockUser.getUserFlag());

        try {
            for (int i = 0;i<15;i++){
            String result = HttpClientKit.post(url+common+lockUser.getDeviceCode()+LockManage.nbiotCtrl,param,"utf8",token.getToken());
            System.out.println(result);
            JSONObject data = JsonKit.parse(result);
            Boolean results = data.getBoolean("result");
            Integer status = data.getInteger("status");
            if (results){
                return true;
               }
             i++;
             Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
